<?php
class BaseAction extends Action {
    protected $uid;//用户ID
    protected $mobile;//用户手机号
    protected $username;//用户名
    protected $email;//用户邮箱
    protected $userinfo;//用户信息
    protected $avatar;//用户头像


    public function __construct(){
        parent::__construct();
        $this->assign('now',TIME_NOW);
        $this->get_config();
        $this->get_deal_cate_list();
        $this->get_help_list();
        $this->get_userinfo();
        if(!$this->get_login_status()){
            $this->assign('request_login',isset($_REQUEST['request_login']) ? $_REQUEST['request_login'] : session('request_login'));
        }else{
            $this->assign('request_login',0);
            $_POST['request_login'] = $_GET['request_login'] = $_REQUEST['request_login'] = '';
        }
        session('request_login',null);
        //删除30分钟后不支付的订单,并更新支持人数
        $list = M('deal_order')->where(array('order_status'=>'0','create_time'=>array('LT',time()-1800)))->field('deal_item_id')->select();
        $deal_item_list = array();
        foreach($list as $v){
            $deal_item_list[] = $v['deal_item_id'];
        }
        if(count($deal_item_list) > 0){
            M('deal_item')->where(array('id'=>array('in',implode(',',$deal_item_list))))->data(array('support_count'=>array('exp','support_count-1')))->save();
            M('deal_order')->where(array('order_status'=>'0','create_time'=>array('LT',time()-1800)))->data(array('order_status'=>'1'))->save();
        }
    }


    protected function checkEmail($inAddress)
    {
        if (filter_var($inAddress, FILTER_VALIDATE_EMAIL)) {
            return true;
        }else{
            return false;
        }
    }

    /**
     * 输出信息
     */
    protected function return_status($status,$info,$exit=true){
        if($this->isAjax()){
            $array = array('status'=>$status,'info'=>$info);
            echo json_encode($array,JSON_HEX_TAG);
        }else{
            if($status == '1'){
                $this->success($info);
            }else{
                $this->error($info);
            }
        }
        if($exit){
            exit();
        }
    }
    /**
     * 检查是否为空
     */
    protected function check_empty($value,$info){
        if(trim($value) == ''){
            if($this->isAjax()){
                $result = array('status'=>'0','info'=>$info);
                exit(json_encode($result));
            }
            else{
                $this->error($info);
            }
        }
    }

    /**
     * 检查是否需要登陆,如果需要登陆才能操作,显示登陆界面
     */
    protected function require_login(){
        if($this->isAjax() && !$this->get_login_status()){
            $array = array('status'=>'0','info'=>'您没有登陆','request_login'=>'1');
            echo json_encode($array,JSON_HEX_TAG);
            exit();
        }
        if(!$this->get_login_status()){
            $redirect_url = !empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $_SERVER['REDIRECT_URL'];
            $referer_url = !empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : $_SERVER['REQUEST_URI'];
            $url_base = parse_url($referer_url);
            parse_str($url_base['query'],$url_param);
            $url_param['request_login'] = '1';
            $referer_url = $url_base['path'] . '?' . http_build_query($url_param);
            session('request_login',1);
            session('redirect_url',$redirect_url);
            redirect($referer_url);
            exit();
        }else{
            session('request_login',0);
            session('redirect_url',null);
        }
    }

    /**
     * 检查是否登陆
     * @return bool
     */
    protected function get_login_status(){
        $this->uid = session('uid');
        $this->mobile = session('mobile');
        $this->username = session('username');
        $this->email = session('email');
        $this->avatar = session('avatar');
        if(!empty($this->uid)){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 发送短消息
     */
    protected function send_sms($tpl_name,$mobile,$data){
        $template  = M('msg_template')->where(array('name'=>$tpl_name))->getField('content');
        if(empty($template)){
            $this->return_status('0' ,'发送类型不存在,请检查');
        }else{
            foreach($data as $k=>$v){
                $template = str_replace('{$'.$k.'}',$v,$template);
            }
        }
        require_once SITE_PATH."system/utils/es_sms.php";
        $sms = new sms_sender();

        $result = $sms->sendSms($mobile,$template);
        if($result['status'])
        {
            $this->return_status('1' ,'发送成功');
        }
        else
        {
            $this->return_status('0' ,'发送失败');
        }
    }


    /**
     * 获取用户信息
     * @return bool|mixed
     */
    protected function get_userinfo(){
        if(!$this->get_login_status()){
            return false;
        }else{
            $this->userinfo =  M('user')->where(array('id'=>$this->uid))->find();
            if(empty($this->userinfo)){
                return false;//用户不存在
            }else{
                unset($this->userinfo['user_pwd']);
                if(empty($this->userinfo['avatar'])){
                    $this->userinfo['avatar_big'] = '/avatar/noavatar_big.png';
                    $this->userinfo['avatar_middle'] = '/avatar/avatar_middle.png';
                    $this->userinfo['avatar_small'] = '/avatar/avatar_small.png';
                }else{
                    $tmp_avatar = pathinfo($this->userinfo['avatar']);
                    $this->userinfo['avatar_big'] = sprintf('%s/%s_big.%s',$tmp_avatar['dirname'],$tmp_avatar['filename'],$tmp_avatar['extension']);
                    $this->userinfo['avatar_middle'] = sprintf('%s/%s_middle.%s',$tmp_avatar['dirname'],$tmp_avatar['filename'],$tmp_avatar['extension']);
                    $this->userinfo['avatar_small'] = sprintf('%s/%s_small.%s',$tmp_avatar['dirname'],$tmp_avatar['filename'],$tmp_avatar['extension']);
                }
                $this->userinfo['user_name'] = !empty($this->username) ? $this->username : $this->userinfo['user_name'];
                $this->assign('user',$this->userinfo);
                return $this->userinfo;
            }
        }
    }

    /**
     * 根据ID获取指定用户信息
     */

    protected function get_user_by_uid($uid){
        $data = M('user')->where(array('id'=>$uid))->limit(1)->find();
        if(isset($data['id'])){
            unset($data['user_pwd']);
            return $data;
        }else{
            return false;
        }
    }

    /**
     * 根据用户名获取指定用户信息
     */
    protected function get_user_by_name($name){
        $data = M('user')->where(array('user_name'=>$name))->limit(1)->find();
        if(isset($data['id'])){
            unset($data['user_pwd']);
            return $data;
        }else{
            return false;
        }
    }


    /**
     * 根据邮箱获取指定用户信息
     */
    protected function get_user_by_email($email){
        $data = M('user')->where(array('email'=>$email))->limit(1)->find();
        if(isset($data['id'])){
            unset($data['user_pwd']);
            return $data;
        }else{
            return false;
        }
    }

    /**
     * 根据手机号获取指定用户信息
     */
    protected function get_user_by_phone($mobile){
        $data = M('user')->where(array('mobile'=>$mobile))->limit(1)->find();
        if(isset($data['id'])){
            unset($data['user_pwd']);
            return $data;
        }else{
            return false;
        }
    }

    protected function get_config(){
        $filename = SITE_PATH.'system/config.php';
        $config = array();
        if(file_exists($filename)){
            $config = include($filename);
        }
        $this->assign('config',$config);
    }

    /**
     * 生成验证码
     */
    public function verify_code(){
        import('ORG.Util.Image');
        Image::buildImageVerify(4,2);
    }

    /**
     * 首页轮播图片
     */
    protected function get_index_image(){
        $list = S('index_image');
        if(empty($list)){
            $list = M('index_image')->where(array('status'=>'1'))->order('sort asc')->limit(INDEX_IMAGE_NUM)->select();
        }
        $this->assign('index_image',$list);
    }

    /**
     * 帮助文章列表
     */
    protected function get_help_list(){
        $list = M('help')->field('id,title,type,url')->order('sort asc')->select();
        foreach($list as &$v){
            if(empty($v['url'])){
                $v['url'] = "/help/{$v['id']}.html";
            }
            if(!empty($v['type'])){
                $v['url'] = "/help/{$v['type']}.html";
            }
        }
        $this->assign('help_list',$list);
    }

    /**
     * 查看文章内容
     */
    protected function get_help_view($id){
        $condition = array();
        if(is_numeric($id)){
            $condition['id'] = $id;
        }else{
            $condition['type'] = $id;
        }
        $data = M('help')->where($condition)->limit(1)->find();
        if(!empty($data)){
            if(!empty($data['url'])){
                $this->redirect($data['url']);
                exit();
            }
            $this->assign('data',$data);
        }else{
            $this->error('文章不存在','/');
        }
    }


    /**
     * 常见问题列表
     */
    protected function get_faq_list(){
        $list = M('faq')->field('id,group,question,answer')->order('`group` asc,sort asc')->select();
        foreach($list as &$v){
            if(empty($v['url'])){
                $v['url'] = "/faq/view/id/{$v['id']}.html";
            }
        }
        $this->assign('faq_list',$list);
    }

    /**
     * 获取众筹分类信息
     */
    protected function get_deal_cate_list(){
        $tmp = M('deal_cate')->order('sort asc')->select();
        foreach($tmp as $k=>$v){
            $list[$v['id']] = $v;
        }
        $this->assign('deal_cate_list',$list);
    }

    /**
     * 获取支付方式
     */
    protected function get_payment_list(){
        $list = M('payment')->where(array('is_effect'=>'1'))->select();
        if(is_array($list)){
            foreach($list as $k=>$v){
                $list[$k]['config'] = unserialize($list[$k]['config']);
            }
        }
        return $list;
    }

    /**
     * 格式化项目信息
     */
    protected function deal_info_format($deal_info){
        $deal_info['end_time'] = max(0,$deal_info['end_time']);
        $deal_info['remain_support_percent'] = ($deal_info['limit_price'] <= $deal_info['support_amount']) ? '100' : ($deal_info['support_amount']/$deal_info['limit_price']*100);
        $deal_info['remain_days'] = ($deal_info['end_time'] >= time()) ? floor(($deal_info['end_time']-time())/86400) : 0;
        $deal_info['remain_days_percent'] = ($deal_info['end_time'] >= time()) ? intval((((time()-$deal_info['begin_time'])/86400)/(($deal_info['end_time']-time())/86400))*100) : 0;
        $deal_info['percent'] = round($deal_info['support_amount']/$deal_info['limit_price']*100);
        $deal_info['remain_days_status'] = '';
        $deal_info['remain_support_status'] = '';
        if($deal_info['begin_time'] > time()){
            $deal_info['remain_days_status'] = '暂未上线';
            $deal_info['remain_support_status'] = '暂未开始';
        }
        if($deal_info['end_time'] < time() && $deal_info['end_time'] != 0){
            $deal_info['remain_days_status'] = '已经过期';
            if($deal_info['limit_price'] <= $deal_info['support_amount']){
                $deal_info['remain_support_status'] = '达成目标';
            }else{
                $deal_info['remain_support_status'] = '众筹失败';
            }
        }
        if(($deal_info['end_time'] > time() || $deal_info['end_time'] == 0 ) && $deal_info['begin_time'] < time()){
            $deal_info['remain_days_status'] = '剩余时间';
            if($deal_info['limit_price'] <= $deal_info['support_amount']){
                $deal_info['remain_support_status'] = '达成目标';
            }else{
                $deal_info['remain_support_status'] = '正在众筹';
            }
        }

        $deal_info['limit_price'] = number_price_format(sprintf('%.2f',$deal_info['limit_price']));
        $deal_info['support_amount'] = sprintf('%.2f',$deal_info['support_amount']);
        $deal_info['pay_amount'] = sprintf('%.2f',$deal_info['pay_amount']);
        $deal_info['delivery_fee_amount'] = sprintf('%.2f',$deal_info['delivery_fee_amount']);
        return $deal_info;
    }

    /**
     * 获取项目列表
     * @param mixed $type 分类ID
     * @param bool $recommend 是否推荐项目
     * @param bool $classic 是否经典项目
     * @param mixed $time_select 是否最新发布项目/即将过期项目 参数值 false/new/need
     * @param mixed $province 指定省份的项目
     * @param mixed $city   指定城市的项目
     * @param mixed $user_id 指定用户发布的项目
     * @param mixed $keyword 项目关键字搜索
     * @param string $order_field 排序字段
     * @param string $order_type 排序类型
     * @param int $page_size 每页取多少条数据
     * @param bool $pagebar 是否调用分页条
     */
    protected function get_deal_list($type=false,$recommend=false,$classic=false,$time_select=false,$province=false,$city=false,$user_id=false,$keyword=null,$status=null,$order_field='sort',$order_type='desc',$page_size=10,$pagebar=false){
        $condition = array();
        $condition['is_effect'] = '1';
        $condition['is_delete'] = '0';
        $where['is_success']  = array('EQ', '1');
        $where['end_time']  = array('EGT', time());
        $where['_logic'] = 'OR';
        $condition['_complex'] = $where;
        if($type){
            $condition['cate_id'] = $type;//查看指定分类的项目
        }
        if($recommend){
            $condition['is_recommend'] = '1';//只查看推荐的项目
        }
        if($classic){
            $condition['is_classic'] = '1';//是否经典项目
        }

        $time_text = '最新上线';
        if($status != '1'){
            if($time_select){
                //$begin_time = strtotime(date('Y-m-d 00:00:00'));
                //$end_time = strtotime(date('Y-m-d 23:59:59'));
                if($time_select == 'new'){
                    $order_field = 'begin_time';
                    $order_type = 'desc';
                    //$condition['end_time'] = array(array('EGT',time()),array('NEQ','0'));
                    $time_text = '最新上线';
                }
                if($time_select == 'need'){
                    unset($condition['_complex']);
                    //$condition['is_success'] = '0';
                    $order_field = 'end_time';
                    $order_type = 'asc';
                    $condition['end_time']  = array('EGT', time(),array('NEQ','0'));
                    $time_text = '即将下线';
                }
                if($time_select == 'high'){
                    $order_field = 'support_count';
                    $order_type = 'desc';
                    //$condition['end_time'] =  array(array('EGT',time()),array('NEQ','0'));
                    $time_text = '金额最高';
                }
                if($time_select == 'like'){
                    $order_field = 'focus_count';
                    $order_type = 'desc';
                    //$condition['end_time'] =  array(array('EGT',time()),array('NEQ','0'));;
                    $time_text = '最受欢迎';
                }
            }else{

            }
        }

        $status_text = '状态';
        if($status != 'all'){
            if($status == 'doing'){
                //众筹中
                $status_text = '众筹中';
                unset($condition['_complex']);
                $condition['end_time']  = array(array('EGT',time()),array('NEQ','0'));
            }
            if($status == 'success'){
                if($time_select != 'like' && $time_select != 'high'){
                    $time_text = '全部';
                }
                //众筹成功
                unset($condition['_complex']);
                $status_text = '众筹成功';
                $condition['is_success'] = '1';
                $condition['end_time']  = array(array('ELT',time()),array('NEQ','0'));
            }
        }else{
            $status_text = '全部';
        }
        $this->assign('time_text',$time_text);
        $this->assign('status_text',$status_text);
        if($province){
            $condition['province'] = $province;
        }
        if($city){
            $condition['city'] = $city;
        }
        if($user_id){
            $condition['user_id'] = $user_id;//只查看指定用户的项目
        }
        if(!is_null($keyword)){
            $condition['name'] = array('LIKE',"%{$keyword}%");
        }

        if($pagebar){
            $deal_total = M('deal')->where($condition)->count();
            $Page = new Page($deal_total,$page_size);
            $this->assign('page',$Page->show_front());
            $this->assign("current_page",$Page->nowPage);
            $deal_list = M('deal')->where($condition)->order("{$order_field} {$order_type}")->limit($Page->firstRow,$Page->listRows)->select();
        }else{
            $deal_list = M('deal')->where($condition)->order("{$order_field} {$order_type}")->limit($page_size)->select();
        }
        //echo M('deal')->_sql();
        foreach($deal_list as $k=>$v)
        {
            $deal_list[$k] = $this->deal_info_format($v);
        }

        $this->assign("deal_list",$deal_list);
    }


    /**
     * 上传图片的通公基础方法
     *
     * @return array
     */
    protected function uploadImage()
    {
        if(C("WATER_MARK")!="")
            $water_mark = WEB_PATH.C("WATER_MARK");  //水印
        else
            $water_mark = "";
        $alpha = C("WATER_ALPHA");   //水印透明
        $place = C("WATER_POSITION");  //水印位置

        import('ORG.Net.UploadFile');
        $upload = new UploadFile();
        //设置上传文件大小
        $upload->maxSize  = C('MAX_IMAGE_SIZE') ;  /* 配置于config */
        //设置上传文件类型

        $upload->allowExts  =  explode(',',C('ALLOW_IMAGE_EXT')); /* 配置于config */
        $dir_name = to_date(get_gmtime(),"Ym");
        if (!is_dir(WEB_PATH."attachment/".$dir_name)) {
            @mkdir(WEB_PATH."attachment/".$dir_name);
            @chmod(WEB_PATH."attachment/".$dir_name, 0777);
        }

        $dir_name = $dir_name."/".to_date(get_gmtime(),"d");
        if (!is_dir(WEB_PATH."attachment/".$dir_name)) {
            @mkdir(WEB_PATH."attachment/".$dir_name);
            @chmod(WEB_PATH."attachment/".$dir_name, 0777);
        }

        $dir_name = $dir_name."/".to_date(get_gmtime(),"H");
        if (!is_dir(WEB_PATH."attachment/".$dir_name)) {
            @mkdir(WEB_PATH."attachment/".$dir_name);
            @chmod(WEB_PATH."attachment/".$dir_name, 0777);
        }



        $save_rec_Path = "/attachment/".$dir_name."/origin/";  //上传时先存放原图
        $savePath = WEB_PATH."attachment/".$dir_name."/origin/"; //绝对路径
        if (!is_dir(WEB_PATH."attachment/".$dir_name."/origin/")) {
            @mkdir(WEB_PATH."attachment/".$dir_name."/origin/");
            @chmod(WEB_PATH."attachment/".$dir_name."/origin/", 0777);
        }

        $upload->saveRule = "uniqid";   //唯一
        $upload->savePath = $savePath;
        if($upload->upload())
        {
            $uploadList = $upload->getUploadFileInfo();
            foreach($uploadList as $k=>$fileItem)
            {
                $file_name = $fileItem['savepath'].$fileItem['savename'];  //上图原图的地址
                //水印图
                $big_save_path = str_replace("origin/","",$savePath);  //大图存放图径
                $big_file_name = str_replace("origin/","",$file_name);

//					Image::thumb($file_name,$big_file_name,'',$big_width,$big_height);
                @file_put_contents($big_file_name,@file_get_contents($file_name));
                if(file_exists($water_mark))
                {
                    Image::water($big_file_name,$water_mark,$big_file_name,$alpha,$place);
                }
                $big_save_rec_Path = str_replace("origin/","",$save_rec_Path);  //上传的图存放的相对路径
                $uploadList[$k]['recpath'] = $save_rec_Path;
                $uploadList[$k]['bigrecpath'] = $big_save_rec_Path;
            }
            return array("status"=>1,'data'=>$uploadList,'info'=>L("UPLOAD_SUCCESS"));
        }
        else
        {
            return array("status"=>0,'data'=>null,'info'=>$upload->getErrorMsg());
        }
    }


    /**
     * 上传文件公共基础方法
     *
     * @return array
     */
    protected function uploadFile()
    {
        import('ORG.Net.UploadFile');
        $upload = new UploadFile();
        //设置上传文件大小
        $upload->maxSize  = C('MAX_IMAGE_SIZE') ;  /* 配置于config */
        //设置上传文件类型

        $upload->allowExts  =  explode(',',C('ALLOW_IMAGE_EXT')); /* 配置于config */
        $dir_name = to_date(get_gmtime(),"Ym");
        if (!is_dir(WEB_PATH."attachment/".$dir_name)) {
            @mkdir(WEB_PATH."attachment/".$dir_name);
            @chmod(WEB_PATH."attachment/".$dir_name, 0777);
        }

        $dir_name = $dir_name."/".to_date(get_gmtime(),"d");
        if (!is_dir(WEB_PATH."attachment/".$dir_name)) {
            @mkdir(WEB_PATH."attachment/".$dir_name);
            @chmod(WEB_PATH."attachment/".$dir_name, 0777);
        }

        $dir_name = $dir_name."/".to_date(get_gmtime(),"H");
        if (!is_dir(WEB_PATH."attachment/".$dir_name)) {
            @mkdir(WEB_PATH."attachment/".$dir_name);
            @chmod(WEB_PATH."attachment/".$dir_name, 0777);
        }



        $save_rec_Path = "/attachment/".$dir_name."/";  //上传时先存放原图
        $savePath = WEB_PATH."attachment/".$dir_name."/"; //绝对路径
        $domain_path = WEB_DOMAIN.$save_rec_Path;


        $upload->saveRule = "uniqid";   //唯一
        $upload->savePath = $savePath;
        if($upload->upload())
        {
            $uploadList = $upload->getUploadFileInfo();
            foreach($uploadList as $k=>$fileItem)
            {
                $uploadList[$k]['recpath'] = $save_rec_Path;
            }
            return array("status"=>1,'data'=>$uploadList,'info'=>L("UPLOAD_SUCCESS"));
        }
        else
        {
            return array("status"=>0,'data'=>null,'info'=>$upload->getErrorMsg());
        }
    }


}